package com.crazymakercircle.innerlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * @Description 利用park unpark 实现交替输出
 * @Date 2021/7/23
 * @Created by Jonathan
 */
public class ParkDemo {
    static Thread t1;
    static Thread t2;
    static Thread t3;


    public static void main(String[] args) {
        ParkUnpark p = new ParkUnpark(5);
        t1 = new Thread(() -> {
            p.print("a", t2);
        }, "a");

        t2 = new Thread(() -> {
            p.print("b", t3);
        }, "b");
        t3 = new Thread(() -> {
            p.print("c", t1);
        }, "c");
        t1.start();
        t2.start();
        t3.start();

        LockSupport.unpark(t2);


    }
}

@Slf4j
class ParkUnpark {
    public int loopNum;

    public ParkUnpark(int loopNum) {
        this.loopNum = loopNum;
    }

    public void print(String str, Thread next) {
        for (int i = 0; i < loopNum; i++) {
            LockSupport.park();
            log.info("str:{}", str);
            LockSupport.unpark(next);
        }
    }

}
